#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
import os
import logging
import data


def joinPath(path):
		jpath = os.path.join(os.path.dirname(__file__), path)
		return jpath


class MainHandler(webapp.RequestHandler):
    def get(self):
		path = joinPath('index.html')
		self.response.out.write(template.render(path, None))


class User(db.Model):
	name = db.StringProperty()
	ranks = db.StringListProperty()


class UserLogin(webapp.RequestHandler):
	def post(self):
		name = self.request.get('id')
		users = User.gql('WHERE name = :1', name)
		user = users.get()
		if user==None:
			user = User()
			user.name = name
			user.put()
		path = joinPath('mainfrm.html')
		self.response.out.write(template.render(path, {'user_id': user.key(), 'user_name': name}))
	
	def get(self):
		key = self.request.get('id')
		if key=='':
			self.redirect('/')
			return
		user = db.get(key)
		if user:
			path = joinPath('mainfrm.html')
			self.response.out.write(template.render(path, {'user_id': user.key(), 'user_name': user.name}))
		else:
			self.redirect('/')


class UserRanks(webapp.RequestHandler):
	def get(self):
		name = self.request.get('name')
		user = User.gql('WHERE name = :1', name).get()
		if user:
			ranks = list()
			for r in user.ranks:
				ranks.append(eval(r))
			path = joinPath('rank.html')
			self.response.out.write(template.render(path, {'ranks': ranks, 'name': name}))


class UserMain(webapp.RequestHandler):
	def get(self):
		key = self.request.get('id')
		user = db.get(key)
		if user:
			path = joinPath('usermain.html')
			self.response.out.write(template.render(path, {'user_id': key, 'scns': data.scns}))
		else:
			self.redirect('/')


class SelectTeam(webapp.RequestHandler):
	def get(self):
		path = joinPath('team.html')
		self.response.out.write(template.render(path, {'jobs': data.jobs}))
	
	def post(self):
		key = self.request.get('id')
		user = db.get(key)
		if not user:
			self.redirect('/')
		scn = data.scnmap.get(self.request.get('scn'))
		fighter = data.jobmap.get(self.request.get('fighter'))
		rogue = data.jobmap.get(self.request.get('rogue'))
		wizard = data.jobmap.get(self.request.get('wizard'))
		cleric = data.jobmap.get(self.request.get('cleric'))
		if not (scn and scn and fighter and rogue and wizard and cleric):
			self.redirect('/')
		else:
			gid = data.game.Start(key, scn, fighter, rogue, wizard, cleric)
			self.redirect('/game?id=%s&gid=%d' % (key, gid))


class GameMain(webapp.RequestHandler):
	def get(self):
		key = self.request.get('id')
		gid = self.request.get('gid')
		path = joinPath('game.html')
		self.response.out.write(template.render(path, {'user_id': key, 'gid': gid}))


class GamePlay(webapp.RequestHandler):
	def get(self):
		param = data.game.Play(self)
		if param:
			path = joinPath('play.html')
			self.response.out.write(template.render(path, param))
		else:
			path = joinPath('errgame.html')
			self.response.out.write(template.render(path, None))
			
	def post(self):
		self.get()


class GameJob(webapp.RequestHandler):
	def get(self):
		key = self.request.get('id')
		player = data.game.GetPlayer(key)
		if player:
			path = joinPath('job.html')
			jobs = list()
			for mem in player.get('team'):
				jobs.append(mem.get('data'))
			self.response.out.write(template.render(path, {'jobs': jobs}))


class Clean(webapp.RequestHandler):
	def get(self):
		old, new = data.game.CleanTimeoutPlayers()
		self.response.out.write('old %d -> current %d' % (old, new))


def main():
    application = webapp.WSGIApplication(
			[
			('/', MainHandler),
			('/login', UserLogin),	
			('/main', UserMain),
			('/ranks', UserRanks),
			('/team', SelectTeam),
			('/game', GameMain),
			('/gamejob', GameJob),
			('/gameplay', GamePlay),
			('/clean', Clean),
				],
                                         debug=False)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
